/**
 * Copyright 2008-2009 HAN.BIFANG
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */
package han.bashe.business.pipeline;

import han.bashe.business.adapter.AdapterHandler;
import han.bashe.business.error.ErrorHandler;
import han.bashe.business.log.LogHandler;
import han.bashe.business.retry.RetryHandler;
import han.bashe.business.security.SecurityHandler;
import han.bashe.business.servicequery.ServiceInfoQueryHandler;
import han.bashe.business.statistics.StatHandler;
import han.bashe.common.message.RequestHelper;

import java.util.UUID;

/**
 * @Author Kent
 */
public class HandlerChain extends Handler {
	
	private Handler route;

	private Handler access;

	private Handler adapter;

	private Handler logger;

	private Handler error;

	private Handler retry;
	
	private Handler stat;
	

	public HandlerChain() {
		route = new ServiceInfoQueryHandler();
		access = new SecurityHandler();

		adapter = new AdapterHandler();
		logger = new LogHandler();
		error = new ErrorHandler();
		retry = new RetryHandler();
		stat = new StatHandler();
	}

	@Override
	public void postProcess(PipelineContext ctx) {
		retry.handle(ctx);
		error.handle(ctx);
		stat.handle(ctx);
	}

	@Override
	public boolean preProcess(PipelineContext ctx) {
		if (ctx.hasError())
			return false;
		RequestHelper h = new RequestHelper(ctx.getRequest());
		if (h.getRequestId() == null) {
			String requestId = UUID.randomUUID().toString().replace("-", "");
			h.setRequestId(requestId);
		}
		if (h.getRetryLogId() != null) {
			ctx.setRetryLogId(h.getRetryLogId());
			h.setLogId(h.getRetryLogId());
		}

		return true;
	}

	@Override
	public void process(PipelineContext ctx) {
		route.handle(ctx);
		// log handle request
		logger.handle(ctx);
		access.handle(ctx);
		adapter.handle(ctx);
		
		// log handle response
		logger.handle(ctx);
		

	}

}
